//操作`dom`：`addItem`,`removeItem`,`changeCompleted`
//以便于dom的专门维护
import { ITodoData } from '../typings.ts';
import TodoTemplate from './TodoTemplate';
import { createItem, findParentNode } from './utils';

class TodoDom extends TodoTemplate {
  //接收一个容器
  private _todoWrapper: HTMLElement;

  constructor(todoWrapper: HTMLElement) {
    super();
    this._todoWrapper = todoWrapper;
  }

  //仅限子类使用
  /**
   * 新增一项节点
   * @param {ITodoData} todo 某一项todo item数据
   */
  protected addItem(todo: ITodoData): void {
    //创建外层div
    //新增样式
    //使用父类的实例方法拿到的模板字符串替换为该节点内容
    const oItem: HTMLElement = createItem(
      'div',
      'todo-item',
      this.todoView(todo)
    );
    //将oItem div挂载到节点上
    this._todoWrapper.appendChild(oItem);
  }

  /**
   * 删除某项节点
   * @param target 被点击的标签元素
   */
  protected removeItem(target: HTMLElement) {
    // 去找 <div class="todo-item"></div>节点
    const oParentNode: HTMLElement = findParentNode(target, 'todo-item');

    //找到该节点就整个移除
    oParentNode.remove();
  }

  /**
   * 更改节点里的completed属性
   * @param {HTMLElement} target 被点击的标签元素
   * @param {boolean} completed completed属性
   */
  protected changeCompleted(target: HTMLElement, completed: boolean) {
    // 去找 <div class="todo-item"></div>节点
    const oParentNode: HTMLElement = findParentNode(target, 'todo-item');

    //找到节点下的span元素 <span style="text-decoration: none">content</span>
    const oContent: HTMLElement = oParentNode.getElementsByTagName('span')[0];

    //更改span标签的样式
    oContent.style.textDecoration = completed ? 'line-through' : 'none';
  }

  /**
   * 根据默认的静态数据初始化一个todolist节点
   * @param todoData
   */
  protected initList(todoData: ITodoData[]) {
    //有值时
    if (todoData.length) {
      const oFrag: DocumentFragment = document.createDocumentFragment();

      todoData.map((todo: ITodoData) => {
        //创建一项节点
        const oItem: HTMLElement = createItem(
          'div',
          'todo-item',
          this.todoView(todo)
        );
        oFrag.appendChild(oItem);
      });
      this._todoWrapper.appendChild(oFrag);
    }
  }
}

export default TodoDom;
